import {Button, Table, TableProps, Flex, TableColumnsType} from 'antd'
import React, {useEffect, useState, forwardRef, useImperativeHandle, useRef} from "react";
import dayjs from "dayjs";
import { useNavigate, useSearchParams } from 'react-router-dom'
import {fileList, IFile, fileDel} from "@/api/file.ts";
import useTable from "@/hooks/useTable.ts";
import useDownload from "@/hooks/useDownload.ts";
import BatchDel from "@/components/file/fileList/BatchDel.tsx";

interface DataType {
    key: React.Key;
    fileName: string;
    size: number;
    time: string;
    fileUID: string
    type: string
    path: string
}

interface IProps {
    contents: Array<{ label: string, uid: string, type: string }>
    setContents: (value: (((prevState: Array<{ label: string, uid: string, type: string }>) => Array<{ label: string, uid: string, type: string }>) | Array<{ label: string, uid: string, type: string }>)) => void
    setSelectFileUID: (value: Array<string>) => void
}

interface IDelMethod {
    showModal: () => void
}
const FileListTable = forwardRef(({ contents, setContents, setSelectFileUID }: IProps, ref) => {
    const [selectionType] = useState<'checkbox' | 'radio'>('checkbox');
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    const batchDelRef = useRef(null)
    const [fileUID, setFileUID] = useState<Array<string>>([])
    const { loading, dataSource, getList, del } = useTable<IFile, { fileUID: string }>(fileList, { fileUID: searchParams.get('fileUID') || '0' })
    const { downloadMethod } = useDownload()
    useImperativeHandle(ref, () => ({
        getList: getList,
        del: del,
        dataSource: dataSource
    }))
    const selectDel = () => {
        del(fileDel, fileUID)
    }
    const fileListTable = (fileUID: string, type: string, label: string) => {
        if (type === 'folder') {
            navigate(`/file/list?fileUID=${fileUID}&type=${type}&label=${label}`)
            const value: Array<{ label: string, uid: string, type: string }> = [...contents, { label, uid: fileUID, type }]
            setContents(value)
        }
    }
    const showModal = (fUID: string) => {
        if (batchDelRef.current) {
            (batchDelRef.current as IDelMethod).showModal()
            setFileUID([fUID])
        }
    }
    const download = async (path: string, fileName: string) => {
        await downloadMethod(path, fileName)
    }
    const preview = (path: string, fileName: string) => {
        // if (filePreviewRef.current) {
        //     (filePreviewRef.current as IPreviewMethod).showModal(path, fileName)
        //     // setFileUID([fUID])
        // }
        navigate(`/view?path=${path}&fileName=${fileName}`)
    }
    const columns: TableColumnsType<DataType> = [
        {
            title: '文件名称',
            dataIndex: 'fileName',
            render: (text: string, { fileUID, type }: DataType) => <a onClick={() => fileListTable(fileUID, type, text)}>{text}</a>,
        },
        {
            title: '文件大小',
            dataIndex: 'size',
            render: (size) => <div>{ size ? `${(Number(size) / 1024).toFixed(2)}KB` : '' }</div>
        },
        {
            title: '更新时间',
            dataIndex: 'time',
            render: (time) => <div>{ dayjs(time).format('YYYY-MM-DD HH:mm:ss') }</div>
        },
        {
            title: '操作',
            render: (_, { type, fileUID, path, fileName }) => (
                <Flex gap='middle' wrap>
                    <BatchDel ref={batchDelRef} selectDel={selectDel} btn={<Button type='text' danger onClick={() => showModal(fileUID)}>删除</Button>} />
                    { type !== 'folder' ? <Button type='link' onClick={() => download(path, fileName)}>下载</Button> : null}
                    {/*{ type !== 'folder' ? <FilePreview ref={filePreviewRef} btn={<Button type='link' onClick={() => preview(path, fileName)}>预览</Button>} />: null}*/}
                    { type !== 'folder' ? <Button type='link' onClick={() => preview(path, fileName)}>预览</Button> : null}
                </Flex>
            )
        }
    ];

    const rowSelection: TableProps<DataType>['rowSelection'] = {
        onChange: (_, selectedRows: DataType[]) => {
            setSelectFileUID(selectedRows.map(item => item.fileUID))
            // del(fileDel, selectFileUID)
        },
        // getCheckboxProps: (record: DataType) => ({
        //     // disabled: record.type === 'folder', // Column configuration not to be checked
        //     name: record.fileName,
        // }),
    };
    useEffect(() => {
        getList()
    }, [searchParams.get('fileUID')]);

    return (
        <Table<DataType> pagination={false} loading={loading} scroll={{ x: 650 }} style={{ overflow: 'auto' }} rowSelection={{ type: selectionType, ...rowSelection }} dataSource={dataSource} columns={columns} />
    )
})

export default FileListTable